package com.ideal.frame.interceptor;

import com.ideal.frame.common.anno.PermissionAnnotation;
import com.ideal.frame.common.dto.ResponseModel;
import com.ideal.frame.common.enumerate.ResponseCode;
import com.ideal.frame.util.ResponseUtil;
import com.ideal.frame.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: jin
 * @CreateTime: 2020-02-25 17:09
 * @Description: 权限拦截器
 */
@Component
@Slf4j
public class PermissionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod method = (HandlerMethod)handler;
        PermissionAnnotation permissionAnno = method.getMethod().getAnnotation(PermissionAnnotation.class);
        if(permissionAnno != null){
            //判断权限
            boolean flag = UserUtils.getCurrentUser().getPermissions()
                    .contains(permissionAnno.value().name());
            if(!flag){
                ResponseUtil.renderJson(response, ResponseModel.error(ResponseCode.AUTH_NO_ROLE));
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }
}
